package com.wss.lsl.test.driven.arithmetic;

import java.util.Stack;

/**
 * 数学算术工具
 * 
 * @author sean
 *
 */
public class MathUtil {

	/**
	 * 计算x的n次方
	 * 
	 * @param x
	 * @param n
	 * @return
	 */
	public static int exp(int x, int n) {
		if (n < 0) {
			throw new IllegalArgumentException("n must be more than zero");
		}

		Stack<Integer> s = new Stack<Integer>();
		int result = 1;
		while (n > 0) {
			if (n % 2 == 0) {
				n /= 2;
				s.push(2);
			} else {
				n -= 1;
				s.push(1);
			}
		}

		int count = 0;
		while (s.size() > 0) {
			if (s.pop() == 2) {
				result *= result;
			} else {
				result *= x;
			}
			count++;
		}
		System.out.println(String.format("计算次数：count=%d", count));

		return result;
	}
}
